﻿//-----------------------------------------------------------------------------
// Filename: SctpHeaderUnitTest.cs
//
// Description: Unit tests for the SctpHeader class.
//
// Author(s):
// Aaron Clauson (aaron@sipsorcery.com)
// 
// History:
// 18 Mar 2021	Aaron Clauson	Created, Dublin, Ireland.
//
// License: 
// BSD 3-Clause "New" or "Revised" License, see included LICENSE.md file.
//-----------------------------------------------------------------------------

using Microsoft.Extensions.Logging;
using Xunit;

namespace SIPSorcery.Net.UnitTests
{
    public class SctpHeaderUnitTest
    {
        private ILogger logger = null;

        public SctpHeaderUnitTest(Xunit.Abstractions.ITestOutputHelper output)
        {
            logger = SIPSorcery.UnitTests.TestLogHelper.InitTestLogger(output);
        }

        /// <summary>
        /// Tests that an SCTP header can be written to and then parsed from a buffer.
        /// </summary>
        [Fact]
        public void RoundtripSctpHeader()
        {
            logger.LogDebug("--> {MethodName}", System.Reflection.MethodBase.GetCurrentMethod().Name);
            logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);

            ushort srcPort = 7;
            ushort dstPort = 8888;
            uint verTag = 234230;

            SctpHeader header = new SctpHeader
            {
                SourcePort = srcPort,
                DestinationPort = dstPort,
                VerificationTag = verTag,
            };

            byte[] buffer = new byte[SctpHeader.SCTP_HEADER_LENGTH];

            header.WriteToBuffer(buffer, 0);

            var rndTripHeader = SctpHeader.Parse(buffer, 0);

            Assert.Equal(srcPort, rndTripHeader.SourcePort);
            Assert.Equal(dstPort, rndTripHeader.DestinationPort);
            Assert.Equal(verTag, rndTripHeader.VerificationTag);
        }

        /// <summary>
        /// Tests that the SCTP header from an INIT packet generated by usrsctp can be 
        /// correctly parsed.
        /// </summary>
        [Fact]
        public void ParseUsrSctpInitHeader()
        {
            byte[] buffer = { 0xdf, 0x90, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 
                              0x6a, 0xb8, 0x0e, 0x99 };

            var sctpHdr = SctpHeader.Parse(buffer, 0);

            Assert.Equal(57232, sctpHdr.SourcePort);
            Assert.Equal(7, sctpHdr.DestinationPort);
            Assert.Equal(0U, sctpHdr.VerificationTag);
            Assert.Equal(0x6ab80e99U, sctpHdr.Checksum);
        }
    }
}
